<template>
  <el-upload
    class="upload-demo"
    action
    :limit="1"
    :http-request="handleFileUpload"
    :before-upload="beforeFileUpload"
    :on-remove="handleRemove"
    :file-list="fileList"
    :on-exceed="handleExceed"
    ref="upgradeUploadFile"
  >
    <el-button
      class="upload-btn"
      icon="el-icon-upload"
      size="small"
    >点击上传</el-button>
  </el-upload>
</template>

<script>
import { Message, Loading } from 'element-ui';
import { parseError } from '../utils';
import { v4 as uuid } from 'uuid';
import { uploadFileApi } from '../api/upload';
import { regularUrl } from '../utils/regular';

export default {
  model: {
    prop: 'fileUrl',
    event: 'update'
  },
  props: {
    fileUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: []
    };
  },
  watch: {
    fileUrl: {
      handler(value) {
        if (!value) this.fileList = [];
      }
    }
  },
  methods: {
    clearFilelist() {
      this.$refs['upgradeUploadFile'].clearFiles();
    },
    handleFileUpload(option) {
      try {
        const [extension] = option.file.name.split('.').reverse();
        if (!extension) return Message.error('文件格式不正确');
        const loadingInstance = Loading.service({
          lock: true,
          text: '文件上传中，请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        const formData = new FormData();
        formData.append('file', option.file, encodeURIComponent(option.file.name));
        uploadFileApi(formData)
          .then(res => {
            this.$emit('update', res);
            this.$emit('file-size', option.file.size);
            this.$emit('file-name', option.file.name);
          })
          .catch(error => Message.error(parseError(error)))
          .finally(() => loadingInstance.close());
      } catch (error) {
        Message.error(parseError(error));
      }
    },
    beforeFileUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 100;
      if (!isLt10M) Message.error('文件大小不能超过100MB');

      return isLt10M;
    },
    handleRemove(file) {
      this.fileUrl = '';
      this.$emit('file-size', 0);
    },
    handleExceed(file, fileList) {
      Message.warning('只能上传一个文件');
    }
  }
};
</script>

<style lang="scss" scoped>
.upload-demo {
  /deep/.el-upload-dragger {
    width: 300px;
    height: 160px;
  }
}
.upload-btn {
  text-align: center;
  font-size: 14px;
  width: 300px;
  height: 40px;
  padding: 0px 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #66b1ff;
}
/deep/.el-icon-upload {
  font-size: 30px;
  margin-left: -30px;
}
/deep/.el-upload-list {
  width: 300px !important;
}
</style>
